﻿using MediatR;
using SuYuanSystem.Applications;
using SuYuanSystem.Domain;
using SuYuanSystem.Repositories;
using SuYuanSystem.WebApi.DTOs;
using SuYuanSystem.WebApi.MedialRs.Commands.UserLogin;

namespace SuYuanSystem.WebApi.MedialRs.CommandHandlers.UserLogin
{
    public class UserLoginCommandHandler : IRequestHandler<UserLoginCommand, ApiResult<List<UserDto>>>
    {
        private readonly IRepository<UserInfo> userInfo;
        private readonly IRepository<Role> repository;

        public UserLoginCommandHandler(IRepository<UserInfo> UserInfo, IRepository<Role> repository)
        {
            userInfo = UserInfo;
            this.repository = repository;
        }
        public async Task<ApiResult<List<UserDto>>> Handle(UserLoginCommand request, CancellationToken cancellationToken)
        {
            try
            {
                ApiResult<List<UserDto>> result = new ApiResult<List<UserDto>>();
                result.statusCode = StatusCode.FaieId;
                result.Message = "登录成功";
                var users = await userInfo.GetAll();
                var roles = await repository.GetAll();
                var user = from a in users
                           join b in roles on a.RoleId equals b.RoleId
                           where a.UserName == request.UserName
                           select new UserDto
                           {
                               UserId = a.UserId,
                               UserName = a.UserName,
                               UserPass = a.UserPass,
                               UserNickname = a.UserNickname,
                               RoleId = a.RoleId,
                               RoleName = b.RoleName
                           };
                var entity = user.FirstOrDefault();
                
                if (entity == null)
                {
                    result.statusCode = StatusCode.FaieId;
                    result.Message = "用户不存在";
                    return result;
                }
                if (entity.UserPass != request.Password)
                {
                    result.statusCode = StatusCode.FaieId;
                    result.Message = "密码错误";
                    return result;
                }
               
                result.statusCode = StatusCode.Success;
                result.Data = new List<UserDto> { new UserDto { UserId = entity.UserId, UserName = entity.UserName, UserPass = entity.UserPass, UserNickname = entity.UserNickname, RoleId = entity.RoleId, RoleName = entity.RoleName } };
                return result;
            }
            catch (Exception ex)
            {
                throw new Exception("An error occurred while processing the login request.", ex);
            }
        }
    }
}
